#!/bin/bash
# 远端镜像名称
DOCKER_NAME=ccr.ccs.tencentyun.com/jack_lq/jack_pay:5-20
# 本地镜像名称
RUN_DOCKER_NAME=subfg-api-cn
# 运行的sh 启动脚本
BIN_DIR=/home/ect_service/docker-data/api/bin
# 配置文件
CONF_DIR=/home/ect_service/docker-data/api/conf
# 日志文件
LOGS_DIR=/home/ect_service/docker-data/api/logs
# 部署通知
REMOTE_BOT_URL=https://open.feishu.cn/open-apis/bot/v2/hook/932a8cf4-4d78-475b-b471-55dba6e24294
# 定义启动方法
function start_docker() {

    # 判断容器是否已经存在并正在运行
    docker ps -a | grep $RUN_DOCKER_NAME &> /dev/null
    if [ $? -eq 0 ]; then
        echo "$RUN_DOCKER_NAME is up, we will stop and remove it!!!!"
        docker stop $RUN_DOCKER_NAME
      echo "$RUN_DOCKER_NAME stop exexcute running!!!"
      docker rm  $RUN_DOCKER_NAME
      echo "$RUN_DOCKER_NAME delete success"
    fi
    # 启动容器并输出日志
    docker run -d --network=host --restart=always  --volume=$CONF_DIR:/subfg/server/conf --volume=$LOGS_DIR:/subfg/server/LOGS_DIR --volume=$BIN_DIR:/subfg/server/bin  --name=$RUN_DOCKER_NAME  $DOCKER_NAME
    echo "$RUN_DOCKER_NAME is starting..."
    #request_bot
}

function start_it_docker() {
     # 判断容器是否已经存在并正在运行
    docker ps -a | grep $RUN_DOCKER_NAME &> /dev/null
    if [ $? -eq 0 ]; then
        echo "$RUN_DOCKER_NAME is up, we will stop and remove it!!!!"
        docker stop $RUN_DOCKER_NAME
      echo "$RUN_DOCKER_NAME stop exexcute running!!!"
      docker rm  $RUN_DOCKER_NAME
      echo "$RUN_DOCKER_NAME delete success"
    fi
    # 启动容器并输出日志
    docker run -it --network=host --restart=always  --volume=$CONF_DIR:/subfg/server/conf --volume=$LOGS_DIR:/subfg/server/LOGS_DIR --volume=$BIN_DIR:/subfg/server/bin  --name=$RUN_DOCKER_NAME  $DOCKER_NAME
    echo "$RUN_DOCKER_NAME is starting..."
    #request_bot
}


#更新docker
function update_docker() {
   # 拉取最新的docker 镜像
   docker pull $DOCKER_NAME
}
function all() {
  update_docker
  start_docker
}
# 部署通知机器人
function request_bot() {
  curl -X POST -H "Content-Type: application/json" -d \
   '{"msg_type":"post","content":{"post":{"zh_cn":{"title":"subFG2.0",  "content":[[{"tag":"text","text":"正式后台subfg-api模块:\n"},{"tag":"a","text":"https://www.iextend.top/","href":"https://www.subfg.com/"}]]}}}}' \
    $REMOTE_BOT_URL
}

#清除旧的docker 镜像, 请谨慎使用
function clear_docker() {
  docker rmi $(docker images | grep "none" | awk '{print $3}')
}
# 赋予文件可执行权限
function empower_file_execute() {
  apt update
  apt install dos2unix -y
  dos2unix $BIN_DIR/server.sh
  dos2unix $BIN_DIR/monitor.sh
  chmod +x $BIN_DIR/server.sh
  chmod +x $BIN_DIR/monitor.sh
}
case "$1" in
  'all')
        all
        ;;
  'update')
        update_docker
        ;;
  'start')
        start_docker
        ;;
  'delete')
        clear_docker
        ;;
  'it')
        start_it_docker
        ;;
  'execute')
        empower_file_execute
        ;;
esac
